//防抖函数
function debounce(func, wait = 500, immediate = false) {
  let timeId: any = -1;
  return function () {
    const context = this;
    const args = [...arguments];
    if (timeId != -1) clearTimeout(timeId);
    let callNow = timeId == -1 ? true : false;
    if (immediate && callNow) func.apply(context, args);
    timeId = setTimeout(() => {
      if (immediate) return (timeId = -1);
      func.apply(context, args);
    }, wait);
  };
}

//节流函数
function throttle(func, wait = 500, immediate = false) {
  let timeId: any = -1;
  return function () {
    const context = this;
    const args = [...arguments];
    if (timeId == -1) {
      if (immediate) func.apply(context, args);
      timeId = setTimeout(() => {
        func.apply(context, args);
        timeId = -1;
      }, wait);
    }
  };
}

//路径取值
function getValByPath(obj, path, defVal = "") {
  if (obj == null) return defVal;
  if (typeof obj !== "object") return defVal;
  if (Array.isArray(obj)) return defVal;
  let k,
    v = obj,
    paths = path.split(".");
  while ((k = paths.shift())) {
    let m;
    if (typeof k == "string") m = k.match(/(\w+)\[(\d+)\]$/);
    if (m) {
      v = v[m[1]];
      paths.unshift(parseInt(m[2]));
    } else {
      v = v[k];
    }
    if (v == undefined) return defVal;
  }
  return v;
}

//路径存值
function setValByPath(obj, path, val) {
  if (obj == null) return;
  if (typeof obj !== "object") return;
  if (Array.isArray(obj)) return;
  let k,
    v = obj,
    paths = path.split(".");
  while ((k = paths.shift())) {
    let m;
    if (typeof k == "string") m = k.match(/(\w+)\[(\d+)\]$/);
    if (m) {
      if (!Array.isArray(v[m[1]])) v[m[1]] = [];
      paths.unshift(parseInt(m[2]));
      if (paths.length != 0) v = v[m[1]];
    } else {
      if (v[k] == undefined || v[k]?.constructor != Object) v[k] = {};
      if (paths.length != 0) v = v[k];
    }
    if (paths.length == 0) {
      v[k] = val;
      break;
    }
  }
}

export { debounce, throttle, getValByPath, setValByPath };
